/**
 * ━━━━━━神兽出没━━━━━━
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃神兽保佑, 永无BUG!
 * 　　　　┃　　　┃Code is far away from bug with the animal protecting
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━感觉萌萌哒━━━━━━
 * Summary: ConnectionToJiucai.java
 * Author : WSh
 * Version: 1.0
 * Date   : 2016年10月27日
 * time   : 上午10:13:20
 */
package com.suning.jiucai.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.alibaba.fastjson.JSONObject;
import com.suning.jiucai.utils.HttpUtils;
import com.suning.jiucai.utils.HttpUtils.Operator;
import com.suning.jiucai.utils.RequestUtils;
import com.suning.jiucai.utils.RequestUtils.MsgType;
import com.suning.jiucai.utils.UrlConstants;


public class ConnectionToJiucai extends AbstractConnection {
	
	public ConnectionToJiucai(Dock dock) {
		super(dock);
	}
	
	private final Logger log = Logger.getLogger(this.getClass().getName());
	
	private class HandshakeException extends RuntimeException {
		private static final long serialVersionUID = 2389502693841442863L;

		public HandshakeException(String message) {
			super(message);
		}
	}
	
	private static final int SUCC = 200;
	
	@Override
	public Node getNode(final Dock dock) {
		if (null == dock) {
			throw new IllegalArgumentException("dock is null");
		}
		if (null == dock.getCustNum() || dock.getCustNum().length() <= 0) {
			throw new IllegalArgumentException("custNum is null");
		}
		final String url = UrlConstants.handshakeUrl + "?custNum=" + dock.getCustNum() + "&nickName=" + dock.getNickName()
				+ "&headPic=" + dock.getHeadPic();
		try {
			return HttpUtils.execute(url, new Operator<Node>() {
				@Override
				public Node doOperator(HttpURLConnection connect) throws IOException {
					BufferedReader br = new BufferedReader(new InputStreamReader(connect.getInputStream()));
					StringBuilder sb = new StringBuilder();
					String temp = "";
					while ((temp = br.readLine()) != null) {
						sb.append(temp);
					}
					final String token;
					final String ip;
					final int port;
					JSONObject jsonObject = JSONObject.parseObject(sb.toString());
					int code = jsonObject.getInteger("code");
					if (SUCC == code) {
						token = jsonObject.getJSONObject("data").getString("token");
						ip = jsonObject.getJSONObject("data").getString("ip");
						port = jsonObject.getJSONObject("data").getIntValue("port");
						br.close();
					} else {
						throw new HandshakeException("handshake pre http token,ip,port result code is not 200.  code = "
								+ code + "  " + jsonObject.getString("msg"));
					}
					return new Node() {
						@Override
						public String getToken() {
							return token;
						}

						@Override
						public int getPort() {
							return port;
						}

						@Override
						public String getIp() {
							return ip;
						}

						@Override
						public String getCustNum() {
							return dock.getCustNum();
						}

						@Override
						public String getNickName() {
							return dock.getNickName();
						}

						@Override
						public String getHeadPic() {
							return dock.getHeadPic();
						}

						@Override
						public String getDeviceId() {
							return dock.getDeviceId();
						}

						@Override
						public int getHbInterval() {
							return dock.getHbInterval();
						}
					};
				}
			});
		} catch (Exception e) {
			throw new HandshakeException("handshake pre occur exception." + e);
		}
	}

	
	@Override
	public void handshake(Node node) {
		try {
			String handshakeJson = RequestUtils.getHandShakeRequest(node.getCustNum(), node.getDeviceId(), node.getHbInterval(), node.getToken()).toJSONString();
			socket.getOutputStream().write(getPack(handshakeJson));
			socket.getOutputStream().flush();
		} catch (IOException e) {
			log.log(Level.WARNING, "socket send handshake info to jiucai server error by tcp. e:" + e);
			throw new InitSocketException(e.getMessage());
		}
	}


	@Override
	public void joinChatRoom(String roomId) {
		String json = RequestUtils.getJoinRoomRequest(roomId).toJSONString();
		sendMsg(json);
	}


	@Override
	public void outChatRoom(String roomId) {
		String json = RequestUtils.getOutRoomRequest(roomId).toJSONString();
		sendMsg(json);
	}


	@Override
	public void sendChatMessage(String toChatRoomId, String fromCustNum, String content, MsgType msgType,
			com.suning.jiucai.utils.Level leval) {
		String json = RequestUtils.getChatMsgRequest(toChatRoomId, fromCustNum, content, msgType, leval).toJSONString();
		sendMsg(json);
	}

}
